/*
 * adc.c
 *
 *  Created on: Oct 27, 2012
 *      Author: malylubo
 */
#include "usart.h"

void initADC(void)
{
	ADC_InitTypeDef ADC_InitStructure;
	  GPIO_InitTypeDef GPIO_InitStructure;

	/* povolime hodiny do A/D prevodniku */
	  RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

	  /* de-initialize ADC */
//	  ADC_DeInit(ADC1);

	  /* Configure PA5 GPIO port pin in Analog input mode (trigger OFF) */
	  	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	  	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_400KHz;
	  	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
	  	  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	  	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	  	  GPIO_Init(GPIOA, &GPIO_InitStructure);



	  /*  ADC configured as follow:
	    - NbrOfChannel = 1 - ADC_Channel_5
	    - Mode = Single ConversionMode(ContinuousConvMode disabled)
	    - Resolution = 12Bits
	    - Prescaler = /1
	    - sampling time 192 */




	  /* ADC Configuration */
	  //ADC_StructInit(&ADC_InitStructure);
	  ADC_StructInit(&ADC_InitStructure);
	  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
	  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
	  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
	  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
	  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	  ADC_InitStructure.ADC_NbrOfConversion = 1;
	  ADC_Init(ADC1, &ADC_InitStructure);

	  /* ADC1 regular channel5 configuration */
	  ADC_RegularChannelConfig(ADC1, ADC_Channel_5, 1, ADC_SampleTime_192Cycles);
	  ADC_DelaySelectionConfig(ADC1, ADC_DelayLength_Freeze);

	  ADC_PowerDownCmd(ADC1, ADC_PowerDown_Idle_Delay, ENABLE);

	  /* Enable ADC1 */
	  ADC_Cmd(ADC1, ENABLE);

	  /* Wait until ADC1 ON status */
	  while (ADC_GetFlagStatus(ADC1, ADC_FLAG_ADONS) == RESET);
  }


  uint16_t ADC1_Read(void)
  {
    uint8_t i;
    uint16_t res;

    /* initialize result */
    res = 0;
    for(i=4; i>0; i--)
    {
    /* start ADC convertion by software */
          ADC_SoftwareStartConv(ADC1);

          /* wait until end-of-covertion */
          while( ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == 0 );
    /* read ADC convertion result */
          res += ADC_GetConversionValue(ADC1);
    }
    return (res>>2);
  }
